﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SDATA;
using SDLL;
using DevComponents.DotNetBar.SuperGrid;
using SCBX;
using SGUI;

namespace SABI
{
    public partial class frm0222 : Form
    {
        string sql = "";
        IGB igb = new IGB(FRM.ConnectString);
        bool _isNew = true;
        string _VoucherID, _BatchID;
        bool _isDuplicate = false;

        public frm0222()
        {
            InitializeComponent();
        }
        public frm0222(bool isNew = true, bool isView = false, string VoucherID = "", bool isDuplicate=false)
        {
            InitializeComponent();
            _isNew = isNew;
            _isDuplicate = isDuplicate;
            btnSave.Visible = !isView;
            txtVoucherNo.Enabled = isNew;
            TDBCboVoucherTypeID.Enabled = isNew;
            btnNext.Visible = isNew;
            GridDB1.PrimaryGrid.ReadOnly = isView;
            _VoucherID = VoucherID;
        }

        private void frm0222_Load(object sender, EventArgs e)
        {
            //loadDATA_Combo();            
        }

        private void ckbVAT_CheckedChanged(object sender, EventArgs e)
        {
            FraVAT.Enabled = chkVAT.Checked;
            if (chkVAT.Checked) { txtTDescription.Text = "Thuế giá trị gia tăng của hàng hóa dịch vụ."; }
            else { txtTDescription.Text = ""; }
        }

        void loadDATA_Combo()
        {
            GUI.ChangeDateFormat(dtpVoucherDate, FRM.SystemDateFormat);
            GUI.ChangeDateFormat(dtpInvoiceDate, FRM.SystemDateFormat);
            GUI.ChangeDateFormat(dtpDueDate, FRM.SystemDateFormat);

            if (_isNew)
            {
                dtpVoucherDate.Value = FRM.DateDue;
                dtpInvoiceDate.Value = FRM.DateDue;
                dtpDueDate.Value = FRM.DateDue;
            }            

            // điều kiện thanh toán
            sql = "SELECT PaymentTermID,PaymentTermName,Duedays,Duetype FROM tb0051 WHERE Disabled=0 ORDER BY PaymentTermID";
            TDBCboPaymentTermID.DataSource = FRM.dt_GET(ref FRM.dt_PaymentTerm, sql);

            // loại chứng từ
            sql = "SELECT * From tb0027 Where Disabled =0 and VoucherGroupID in ('22' ,'99') Order by VoucherTypeID";
            TDBCboVoucherTypeID.DataSource = FRM.dt_GET(ref FRM.dt_VoucherType, sql);
            TDBCboVoucherTypeID.SelectedValue = "BH";

            // loại tiền
            sql = "Select * From tb0024 Where Disabled =0 Order by CurrencyID";
            TDBCboCurrencyID.DataSource = FRM.dt_GET(ref FRM.dt_Currency, sql);
            TDBCboCurrencyID.SelectedValue = FRM.CurrencyID;         

            // đối tượng
            TDBCboObjectID.DataSource = FRM.dt_Object;
            TDBCboObjectIDVAT.DataSource = FRM.dt_Object;
            TDBCboVATObjectID.DataSource = FRM.dt_Object;

            // tài khoản            
            sql = "Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID in ('G03','G04','G05','G07') Order by AccountID";
            DataTable dt_tb0025_CreditAccount = FRM.GetDataTable(sql);
            TDBCboCreditAccountID.DataSource = dt_tb0025_CreditAccount;
            sql = "Select * From tb0025 Where Disabled =0 and IsNotShow =0 and GroupID <> 'G00' Order by AccountID";
            DataTable dt_tb0025_DebitAccount = FRM.GetDataTable(sql);
            TDBCboDebitAccountID.DataSource = dt_tb0025_DebitAccount;

            SCBX.GridMultiComboBox DebitAccountID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clDebitAccountID"].EditControl;
            DebitAccountID.ColumnWidth = new string[] { "90", "200"};
            DebitAccountID.SourceDataHeader = new string[] { "Mã TK Nợ", "Tên TK Nợ" };
            DebitAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            DebitAccountID.StringFilter = "AccountID LIKE '{0}%'";
            DebitAccountID.DisplayColumnNo = 0;
            DebitAccountID.DataSource = dt_tb0025_DebitAccount;

            SCBX.GridMultiComboBox CreditAccountID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clCreditAccountID"].EditControl;
            CreditAccountID.ColumnWidth = new string[] { "90", "200" };
            CreditAccountID.SourceDataHeader = new string[] { "Mã TK Có", "Tên TK Có" };
            CreditAccountID.SourceDataString = new string[] { "AccountID", "AccountName" };
            CreditAccountID.StringFilter = "AccountID LIKE '{0}%'";
            CreditAccountID.DisplayColumnNo = 0;
            CreditAccountID.DataSource = dt_tb0025_CreditAccount;
            
            // loại hóa đơn
            sql = "Select * From tb0029 Where Disabled =0 and IsVATIn = 0 Order by VATTypeID";
            TDBCboVATTypeID.DataSource = FRM.dt_GET(ref FRM.dt_VATType, sql);

            // nhóm thuế
            sql = "Select * From tb0030 Where Disabled =0 Order by VATGroupID";
            TDBCboVATGroupID.DataSource = FRM.dt_GET(ref FRM.dt_VATGroup, sql); 

            // khoản mục [Mã phân tích]
            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A01' Order by AnaID";
            SCBX.GridMultiComboBox clAna01ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna01ID"].EditControl;
            clAna01ID.ColumnWidth = new string[] { "100", "150", "150"};
            clAna01ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna01ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes"};
            clAna01ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna01ID.DisplayColumnNo = 0;
            clAna01ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A02' Order by AnaID";
            SCBX.GridMultiComboBox clAna02ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna02ID"].EditControl;
            clAna02ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna02ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna02ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna02ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna02ID.DisplayColumnNo = 0;
            clAna02ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A03' Order by AnaID";
            SCBX.GridMultiComboBox clAna03ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna03ID"].EditControl;
            clAna03ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna03ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna03ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna03ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna03ID.DisplayColumnNo = 0;
            clAna03ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A04' Order by AnaID";
            SCBX.GridMultiComboBox clAna04ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna04ID"].EditControl;
            clAna04ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna04ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna04ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna04ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna04ID.DisplayColumnNo = 0;
            clAna04ID.DataSource = FRM.GetDataTable(sql);

            sql = "Select * From tb0031 Where Disabled =0 And AnaTypeID = 'A05' Order by AnaID";
            SCBX.GridMultiComboBox clAna05ID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clAna05ID"].EditControl;
            clAna05ID.ColumnWidth = new string[] { "100", "150", "150" };
            clAna05ID.SourceDataHeader = new string[] { "Mã phân tích", "Tên phân tích", "Ghi chú" };
            clAna05ID.SourceDataString = new string[] { "AnaID", "AnaName", "Notes" };
            clAna05ID.StringFilter = "AnaID LIKE '{0}%' OR AnaName LIKE '%{0}%'";
            clAna05ID.DisplayColumnNo = 0;
            clAna05ID.DataSource = FRM.GetDataTable(sql);

            // mặt hàng
            SCBX.GridMultiComboBox clInventoryID = (SCBX.GridMultiComboBox)GridDB1.PrimaryGrid.Columns["clInventoryID"].EditControl;
            clInventoryID.ColumnWidth = new string[] { "80", "170", "100", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" };
            clInventoryID.SourceDataHeader = new string[] { "Mã hàng", "Tên hàng", "Mã ĐV Tính" };
            clInventoryID.SourceDataString = new string[] { "InventoryID", "InventoryName", "UnitID", "AccountID", "SalesAccountID", "I01ID", "I02ID", "I03ID", "I04ID", "I05ID" };
            clInventoryID.StringFilter = "InventoryID LIKE '{0}%' OR InventoryName LIKE '%{0}%'";
            clInventoryID.DisplayColumnNo = 0;
            clInventoryID.DataSource = FRM.dt_Inventory;

        }

        private void TDBCboCurrencyID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtExchangeRate.Text = TDBCboCurrencyID.SelectedItem != null?string.Format("{0:#,#.00}",double.Parse(TDBCboCurrencyID.SelectedItem.ItemData[2])):"";
            if (GridDB1.PrimaryGrid.Rows.Count > 0) { Cal_Price(); }
        }

        private void TDBCboObjectID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TDBCboObjectID.SelectedItem != null)
            {
                txtObjectName.Text = TDBCboObjectID.SelectedItem.ItemData[1];
                TDBCboVATObjectID.SelectedValue = TDBCboObjectID.Text;
                if (chkVAT.Checked) { TDBCboObjectIDVAT.SelectedValue = TDBCboObjectID.Text; }
            }
            else
                txtObjectName.Text = "";
        }

        private void TDBCboVATObjectID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TDBCboVATObjectID.SelectedItem != null)
            {
                txtVATObjectName.Text = TDBCboVATObjectID.SelectedItem.ItemData[1];
                txtVATObjectAddress.Text = TDBCboVATObjectID.SelectedItem.ItemData[2];
            }
            else
            {
                txtVATObjectName.Text = "";
                txtVATObjectAddress.Text = "";
            }            
        }

        private void TDBCboObjectIDVAT_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtObjectNameVAT.Text = TDBCboObjectIDVAT.SelectedItem != null?TDBCboObjectIDVAT.SelectedItem.ItemData[1]:"";
        }

        private void TDBCboPaymentTermID_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtPaymentTermName.Text = TDBCboPaymentTermID.SelectedItem != null ? TDBCboPaymentTermID.SelectedItem.ItemData[1] : "";
        }

        private void txtVATConvertedAmount_ValueChanged(object sender, EventArgs e)
        {
            if (txtExchangeRate.Value == 0)
            {
                txtVATAmount.Value = 0.0;
                return;
            }
            txtVATAmount.Value = txtVATConvertedAmount.Value / txtExchangeRate.Value;
            Cal_Price();
        }

        private void ChkVAT_CheckedChanged(object sender, EventArgs e)
        {
            FraVAT.Enabled = chkVAT.Checked;
            txtTDescription.Text = chkVAT.Checked?"Thuế giá trị gia tăng của hàng hóa, dịch vụ":"";
            if(!chkVAT.Checked)
            {
                TDBCboObjectIDVAT.Text = "";
                txtObjectNameVAT.Text = "";
                TDBCboDebitAccountID.Text = "";
                TDBCboCreditAccountID.Text = "";
                TDBCboVATGroupID.Text = "";
                txtVATAmount.Value = 0.0;
                txtVATConvertedAmount.Value = 0.0;
            }
        }

        private void txtExchangeRate_ValueChanged(object sender, EventArgs e)
        {
            Cal_Price();
        }

        private void GridDB1_EndEdit(object sender, DevComponents.DotNetBar.SuperGrid.GridEditEventArgs e)
        {
            GridDB1_ValueColumnChanged(e.GridCell.RowIndex, e.GridCell.ColumnIndex);
        }

        private void Cal_Price()
        {
            if (txtExchangeRate.Text == null)
            {
                MessageBox.Show("Vui lòng chọn loại tiền!");
                return;
            }
            double Total = 0;
            int Orders = 1;
            for(int i=0; i<GridDB1.PrimaryGrid.Rows.Count;i++)
            {
                if (GridDB1.PrimaryGrid.GetCell(i, 1).Value != null)
                {
                    GridDB1.PrimaryGrid.GetCell(i, 0).Value = Orders;
                    if (GridDB1.PrimaryGrid.GetCell(i, 1).Value.ToString() == "") { continue; }
                    GridDB1.PrimaryGrid.GetCell(i, 6).Value = (GridDB1.PrimaryGrid.GetCell(i, 3).Value==null?0.0:double.Parse(GridDB1.PrimaryGrid.GetCell(i, 3).Value.ToString())) * (GridDB1.PrimaryGrid.GetCell(i, 5).Value==null?0.0:double.Parse(GridDB1.PrimaryGrid.GetCell(i, 5).Value.ToString()));
                    GridDB1.PrimaryGrid.GetCell(i, 7).Value = (GridDB1.PrimaryGrid.GetCell(i, 6).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 6).Value.ToString())) *txtExchangeRate.Value;
                    Total = Total + (GridDB1.PrimaryGrid.GetCell(i, 7).Value == null ? 0.0 : double.Parse(GridDB1.PrimaryGrid.GetCell(i, 7).Value.ToString()));
                    Orders += 1;
                }
                else
                {
                    GridDB1.PrimaryGrid.GetCell(i, 0).Value = null;
                }
            }
            Total += txtVATConvertedAmount.Value;
            lblTotal.Text = string.Format("{0:#,#.00}", Total);
        }

        private void TDBCboVoucherTypeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            if (_isNew) { (Application.OpenForms["frm0256"] as frm0256).CloseTab(); }
            else { Close(); }
            
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            if (!Check_Form()) { return; }
            if (!Check_Table()) { return; }
            if (_isNew)
            {
                if (DLL01.GetID("tb0191", "VoucherNo", txtVoucherNo.Text, "", FRM.ConnectString))
                {
                    if (DLL02.Confirm("Số chứng từ này đã có. Bạn có muốn tạo số chứng từ mới không?", "Xác nhận"))
                    {
                        DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
                    }
                    return;
                }
            }
            Save_Table();
        }

        private bool Check_Form()
        {
            if(TDBCboVoucherTypeID.Text=="")
            {
                DLL02.Alert("Bạn phải chọn loại chứng từ");
                TDBCboVoucherTypeID.Focus();
                return false;
            }
            else if (TDBCboCurrencyID.Text=="")
            {
                DLL02.Alert("Bạn phải chọn loại tiền");
                TDBCboCurrencyID.Focus();
                return false;
            }
            else if (TDBCboObjectID.Text == "")
            {
                DLL02.Alert("Bạn phải chọn đối tượng");
                TDBCboObjectID.Focus();
                return false;
            }
            else if (chkVAT.Checked)
            {
                if (TDBCboObjectIDVAT.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn đối tượng thuế GTGT");
                    TDBCboObjectIDVAT.Focus();
                    return false;
                }
                else if (TDBCboDebitAccountID.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn tài khoản Nợ");
                    TDBCboDebitAccountID.Focus();
                    return false;
                }
                else if (TDBCboCreditAccountID.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn tài khoản Có");
                    TDBCboCreditAccountID.Focus();
                    return false;
                }
                else if (TDBCboVATGroupID.Text == "")
                {
                    DLL02.Alert("Bạn phải chọn nhóm thuế");
                    TDBCboVATGroupID.Focus();
                    return false;
                }
            }
            //Check ngày hạch toán
            //....

            return true;
        }

        private bool Check_Table()
        {
            GridDB1.Update();
            if (GridDB1.PrimaryGrid.Rows.Count < 2)
            {
                DLL02.Alert("Bạn phải nhập chi tiết hóa đơn");
                return false;
            }
            else if(GridDB1.PrimaryGrid.Rows.Count>0)
            {
                int count_valid = 0;
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                {
                    if (GridDB1.PrimaryGrid.GetCell(i, 0).Value == null || GridDB1.PrimaryGrid.GetCell(i, 1).Value == null) { continue; }
                    if (GridDB1.PrimaryGrid.GetCell(i, 1).Value.ToString().Trim() == "") { continue; }
                    count_valid++;
                }
                if (count_valid == 0)
                {
                    GridDB1.PrimaryGrid.Rows.Clear();
                    DLL02.Alert("Bạn phải nhập chi tiết hóa đơn");
                    return false;
                }
            }
            return true;
        }

        private void Delete_Record()
        {
            // xóa chi tiết phiếu bán hàng
            sql = string.Format("DELETE tb0191 Where DivisionID = '{0}' AND VoucherID = '{1}' AND BatchID = '{2}' AND TransactionTypeID = 'T04' ", FRM.DivisionID, _VoucherID, _BatchID);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);

            // xóa thuế của phiếu bán hàng
            sql = string.Format("DELETE tb0191 Where DivisionID = '{0}' AND VoucherID = '{1}' AND BatchID = '{2}' AND TransactionTypeID = 'T14' ", FRM.DivisionID, _VoucherID, _BatchID);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);
        }

        private void Save_Table()
        {
            // Lấy [VoucherID, BatchID]

            string VoucherID = _VoucherID;
            string BatchID = _BatchID;
            if(_isNew)
            {
                VoucherID = DLL01.Get_VoucherID(FRM.ConnectString, "tb0191", "AV", FRM.Year, "");
                BatchID = DLL01.Get_BatchID(FRM.ConnectString, "tb0191", "AB", FRM.Year, "");
            }
            else
            {
                Delete_Record();
            }

            string sql = "";

            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                if (GridDB1.PrimaryGrid.GetCell(i, 0).Value == null || GridDB1.PrimaryGrid.GetCell(i, 1).Value == null) { continue; }
                if (GridDB1.PrimaryGrid.GetCell(i, 1).Value.ToString().Trim()=="") { continue; }

                string TransactionID = DLL01.Get_TransactionID(FRM.ConnectString, "tb0191", "AT", FRM.Year, "");

                sql += "INSERT tb0191 (VoucherID,BatchID,TransactionID,TableID,DivisionID,TranMonth,TranYear,TransactionTypeID,";
                sql += "CurrencyID,ObjectID,CreditObjectID,VATNo, VATObjectID, VATObjectName, VATObjectAddress, DebitAccountID, CreditAccountID, ExchangeRate,";
                sql += "UnitPrice, OriginalAmount, ConvertedAmount,IsStock, VoucherDate, InvoiceDate,";
                sql += "VoucherTypeID, VATTypeID, VATGroupID, VoucherNo, Serial, InvoiceNo, Orders,";
                sql += "EmployeeID, SenderReceiver, SRDivisionName, SRAddress, VDescription, BDescription, TDescription,";
                sql += "Quantity, InventoryID, UnitID, Status, IsAudit, IsCost,";
                sql += "Ana01ID, Ana02ID, Ana03ID, Ana04ID, Ana05ID,";
                sql += "InventoryName1,TypeVoice, DueDate, PaymentTermID, ";
                sql += "CreateDate, CreateUserID, LastModifyDate, LastModifyUserID, Barcode)";
                sql += "VALUES(";
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',N'{7}',", VoucherID, BatchID, TransactionID, "tb0191", FRM.DivisionID, FRM.Month, FRM.Year, "T04"); //T04: Doanh số bán hàng
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',N'{7}',N'{8}',N'{9}',", TDBCboCurrencyID.Text, TDBCboObjectID.Text, DBNull.Value, txtVATNo.Text, TDBCboVATObjectID.Text, txtVATObjectName.Text, txtVATObjectAddress.Text, GridDB1.PrimaryGrid.GetCell(i, 8).Value, GridDB1.PrimaryGrid.GetCell(i, 9).Value, txtExchangeRate.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB1.PrimaryGrid.GetCell(i, 5).Value, GridDB1.PrimaryGrid.GetCell(i, 6).Value, GridDB1.PrimaryGrid.GetCell(i, 7).Value, chkIsStock.Checked?"1":"0", dtpVoucherDate.Value.Date, dtpInvoiceDate.Value.Date);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", TDBCboVoucherTypeID.Text, TDBCboVATTypeID.Text, TDBCboVATGroupID.Text, txtVoucherNo.Text, txtSerial.Text, txtInvoiceNo.Text, GridDB1.PrimaryGrid.GetCell(i, 0).Value);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',", DBNull.Value, txtVATObjectName.Text, txtVATObjectName.Text, txtVATObjectAddress.Text, txtVDescription.Text, txtBDescription.Text, GridDB1.PrimaryGrid.GetCell(i, 10).Value);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", GridDB1.PrimaryGrid.GetCell(i, 3).Value, GridDB1.PrimaryGrid.GetCell(i, 1).Value, GridDB1.PrimaryGrid.GetCell(i, 4).Value, 0,0,0);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", GridDB1.PrimaryGrid.GetCell(i, 11).Value, GridDB1.PrimaryGrid.GetCell(i, 12).Value, GridDB1.PrimaryGrid.GetCell(i, 13).Value, GridDB1.PrimaryGrid.GetCell(i, 14).Value, GridDB1.PrimaryGrid.GetCell(i, 15).Value);
                sql += string.Format("N'{0}',N'{1}', {2}, '{3}',", GridDB1.PrimaryGrid.GetCell(i, 2).Value, txtTypeVoice.Text, dtpDueDate.Checked ? "'" + dtpDueDate.Value.ToShortDateString() + "'" : "NULL", TDBCboPaymentTermID.Text);
                sql += string.Format("GETDATE(),N'{0}',GETDATE(),N'{0}',N'{1}')", FRM.UserName, DBNull.Value);

                DATA.ExecuteNonQuery(sql, FRM.ConnectString, false);
            }

            if (chkVAT.Checked)
            {

                string TransactionID = DLL01.Get_TransactionID(FRM.ConnectString, "tb0191", "AT", FRM.Year, "");

                sql = "Insert tb0191 (PaymentTermID,VoucherID,BatchID,TransactionID,TableID, DivisionID,TranMonth,TranYear,TransactionTypeID,";
                sql += " CurrencyID, ObjectID, VATObjectID,";
                sql += " VATObjectName, VATNo,VATObjectAddress, SRDivisionName, SRAddress, SenderReceiver, ";
                sql += " CreditAccountID, DebitAccountID, ExchangeRate, OriginalAmount, ConvertedAmount, VoucherDate, DueDate,";
                sql += " OriginalAmountCN,ExchangeRateCN,CurrencyIDCN, ";
                sql += " InvoiceDate, VoucherTypeID, VATTypeID, VATGroupID, VoucherNo, Serial, TypeVoice,";
                sql += " InvoiceNo, Orders, EmployeeID, RefNo01,RefNo02, VDescription, BDescription, TDescription, ";
                sql += " Quantity, UnitPrice, InventoryID, UnitID, Status, IsAudit, OrderID, ";
                sql += " ImTaxOriginalAmount, ImTaxConvertedAmount, ExpenseOriginalAmount, ExpenseConvertedAmount, ";
                sql += " Ana01ID, Ana02ID, Ana03ID, Ana04ID,Ana05ID,";
                sql += " CreateDate, CreateUserID, LastModifyDate, LastModifyUserID, Barcode) Values(";

                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}', '{5}',N'{6}',N'{7}',N'{8}',", TDBCboPaymentTermID.Text, VoucherID, BatchID, TransactionID, "tb0191", FRM.DivisionID, FRM.Month, FRM.Year, "T14"); //T04: Doanh số bán hàng
                sql += string.Format("N'{0}',N'{1}',N'{2}',", TDBCboCurrencyID.Text, TDBCboObjectIDVAT.Text, TDBCboVATObjectID.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',", txtVATObjectName.Text, txtVATNo.Text, txtVATObjectAddress.Text, txtVATObjectName.Text, txtVATObjectAddress.Text, txtVATObjectName.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',{6},", TDBCboCreditAccountID.Text, TDBCboDebitAccountID.Text, txtExchangeRate.Value, txtVATAmount.Value, txtVATConvertedAmount.Value, dtpVoucherDate.Value, dtpDueDate.Checked?"'"+dtpDueDate.Value.ToShortDateString()+"'":"NULL");
                sql += string.Format("N'{0}',N'{1}',N'{2}',", txtVATAmount.Value, txtExchangeRate.Value, TDBCboCurrencyID.Text);
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}', '{6}',", dtpInvoiceDate.Value, TDBCboVoucherTypeID.Text, TDBCboVATTypeID.Text, TDBCboVATGroupID.Text, txtVoucherNo.Text, txtSerial.Text, txtTypeVoice.Text);
                sql += string.Format("N'{0}',N'0',NULL,NULL,NULL,N'{1}',N'{2}',N'{3}',", txtInvoiceNo.Text, txtVDescription.Text, txtBDescription.Text, txtTDescription.Text);
                sql += "NULL,NULL,NULL,NULL,0,0, NULL,";
                sql += "NULL,NULL,NULL,NULL,";
                sql += string.Format("N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", GridDB1.PrimaryGrid.GetCell(0, 11).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 12).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 13).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 14).Value.ToString(), GridDB1.PrimaryGrid.GetCell(0, 15).Value.ToString());
                sql += string.Format("GETDATE(),N'{0}',GETDATE(),N'{0}',N'{1}')", FRM.UserName, DBNull.Value);

                DATA.ExecuteNonQuery(sql, FRM.ConnectString, true);

            }

            if(_isNew||_isDuplicate)
            {
                igb.SaveNewKey();
                (Application.OpenForms["frm0256"] as frm0256).loadDATA_Grid();
            }                        
            DLL02.Info("Lưu dữ liệu thành công");
            btnSave.Enabled = false;
            btnOutputWareHouse.Enabled = true;
        }

        private void cmdNext_Click(object sender, EventArgs e)
        {
            
            txtVDescription.Text = "";
            txtBDescription.Text = "";
            txtTDescription.Text = "";
            txtInvoiceNo.Text = "";
            txtSerial.Text = "";
            txtVATNo.Text = "";
            txtVDescription.Text = "";
            txtVATNo.Text = "";

            TDBCboDebitAccountID.Clear();
            TDBCboObjectIDVAT.Clear();
            TDBCboPaymentTermID.Clear();
            TDBCboObjectID.Clear();
            TDBCboVATObjectID.Clear();
            chkVAT.Checked = false;

            frm0222_Shown(null, null);
            btnSave.Enabled = true;
            lblTotal.Text = "0.00";

            GridDB1.PrimaryGrid.Rows.Clear();

        }

        private void frm0222_Shown(object sender, EventArgs e)
        {
            loadDATA_Combo();
            if (!_isNew)
            {
                loadDATA_Edit();
            }
        }

        void loadDATA_Edit()
        {
            sql = "Select * , tb0054.IsSource,tb0054.IsLimitDate,tb0054.IsLocation, tb0054.IsStocked, tb0054.AccountID as IsDebitAccountID";
            sql+= " From tb0191   Left Join tb0054 On tb0191.InventoryID = tb0054.InventoryID   ";
            sql += " Where VoucherID = '" + _VoucherID + "' And TransactionTypeID = 'T04' order by Orders";
            DataTable dtT = FRM.GetDataTable(sql);
            if (dtT == null)
            {
                DLL02.Info("Bảng dữ liệu không tồn tại hoặc mất kết nối cơ sở dữ liệu\nVui lòng thử lại");
                Close();
                return;
            }
            else if (dtT.Rows.Count == 0)
            {
                DLL02.Info("Phiếu bán hàng này không tồn tại!");
                Close();
                return;
            }
            GridDB1.PrimaryGrid.DataSource = dtT;

            _BatchID = dtT.Rows[0]["BatchID"].ToString();
            TDBCboVoucherTypeID.Text = dtT.Rows[0]["VoucherTypeID"].ToString();
            txtVoucherNo.Text = dtT.Rows[0]["VoucherNo"].ToString();
            txtVDescription.Text = dtT.Rows[0]["VDescription"].ToString();
            TDBCboCurrencyID.SelectedValue = dtT.Rows[0]["CurrencyID"].ToString();
            DateTime dateT;
            dtpVoucherDate.Value = DateTime.TryParse(dtT.Rows[0]["VoucherDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["VoucherDate"].ToString()) : DateTime.Now;
            dtpInvoiceDate.Value = DateTime.TryParse(dtT.Rows[0]["InvoiceDate"].ToString(), out dateT) ? DateTime.Parse(dtT.Rows[0]["InvoiceDate"].ToString()) : DateTime.Now;
            if (DateTime.TryParse(dtT.Rows[0]["DueDate"].ToString(), out dateT)) { dtpDueDate.Value = dateT; dtpDueDate.Checked = true; }            
            txtTypeVoice.Text = dtT.Rows[0]["TypeVoice"].ToString();
            txtSerial.Text = dtT.Rows[0]["Serial"].ToString();
            txtInvoiceNo.Text = dtT.Rows[0]["InvoiceNo"].ToString();
            TDBCboVATTypeID.SelectedValue = dtT.Rows[0]["VATTypeID"].ToString();
            txtExchangeRate.Text = dtT.Rows[0]["ExchangeRate"].ToString();
            TDBCboObjectID.SelectedValue = dtT.Rows[0]["ObjectID"].ToString();
            TDBCboVATObjectID.SelectedValue = dtT.Rows[0]["VATObjectID"].ToString();
            txtVATNo.Text = dtT.Rows[0]["VATNo"].ToString();
            txtBDescription.Text = dtT.Rows[0]["BDescription"].ToString();
            TDBCboPaymentTermID.Text = dtT.Rows[0]["PaymentTermID"].ToString();
            chkIsStock.Checked = dtT.Rows[0]["IsStock"].ToString() == "1" ? true : false;

            sql = string.Format("Select * From tb0191 Where VoucherID = '{0}' And TransactionTypeID = 'T14' ", _VoucherID);
            dtT = FRM.GetDataTable(sql);
            if(dtT.Rows.Count>0)
            {
                chkVAT.Checked = true;

                TDBCboObjectIDVAT.SelectedValue = dtT.Rows[0]["ObjectID"].ToString();
                TDBCboDebitAccountID.SelectedValue = dtT.Rows[0]["DebitAccountID"].ToString();
                TDBCboCreditAccountID.SelectedValue = dtT.Rows[0]["CreditAccountID"].ToString();
                TDBCboVATGroupID.SelectedValue = dtT.Rows[0]["VATGroupID"].ToString();
                txtTDescription.Text = dtT.Rows[0]["TDescription"].ToString();
                txtVATAmount.Text = dtT.Rows[0]["OriginalAmount"].ToString();
                txtVATConvertedAmount.Text = dtT.Rows[0]["OriginalAmount"].ToString();
            }           
            
            if(_isDuplicate)
            {
                _isNew = true;
                TDBCboVoucherTypeID.Enabled = true;
                txtVoucherNo.Enabled = true;
                DLL01.Get_VoucherNo(ref igb, FRM.ConnectString, TDBCboVoucherTypeID.Text, txtVoucherNo, "tb0191", FRM.Month, FRM.Year, FRM.DivisionID);
            }
            Cal_Price();
        }

        private void GridDB1_ValueColumnChanged(int RowIndex, int ColumnIndex)
        {
            GridPanel e = GridDB1.PrimaryGrid;
            GridColumn gc = e.Columns[ColumnIndex];

            if (gc.EditControl.GetType() == typeof(SCBX.GridMultiComboBox))
            {
                GridRow gr = (GridRow)e.GridPanel.ActiveRow;
                GridMultiComboBox cl = (GridMultiComboBox)gc.EditControl;

                //if (cl.SelectedItem == null) { return; }
                if (cl.SelectedItem == null && e.Columns[ColumnIndex].Name == "clInventoryID") //e.GridCell.Value == null || 
                {
                    gr["clInventoryName"].Value = null;
                    gr["clQuantity"].Value = 0;
                    gr["clUnitID"].Value = null;
                    gr["clUnitPrice"].Value = 0;
                    gr["clOriginalAmount"].Value = 0;
                    gr["clConvertedAmount"].Value = 0;
                    Cal_Price();
                    return;
                }
                // if (e.GridCell.Value.ToString().Trim() == "") { return; }
                if (e.Columns[ColumnIndex].Name == "clInventoryID")
                {
                    gr["clInventoryName"].Value = cl.SelectedItem.ItemData[1];
                    gr["clQuantity"].Value = 1.0;
                    gr["clUnitID"].Value = cl.SelectedItem.ItemData[2];
                    gr["clUnitPrice"].Value = 0;//cl.SelectedItem.ItemData[3] != null ? cl.SelectedItem.ItemData[3] : "0"; //3-7 la gia
                    gr["clDebitAccountID"].Value = cl.SelectedItem.ItemData[3];
                    gr["clCreditAccountID"].Value = cl.SelectedItem.ItemData[4];
                    gr["clAna01ID"].Value = cl.SelectedItem.ItemData[5];
                    gr["clAna02ID"].Value = cl.SelectedItem.ItemData[6];
                    gr["clAna03ID"].Value = cl.SelectedItem.ItemData[7];
                    gr["clAna04ID"].Value = cl.SelectedItem.ItemData[8];
                    gr["clAna05ID"].Value = cl.SelectedItem.ItemData[9];

                }
            }
            Cal_Price();
        }

        private void btnVoucherTypeIDSetting_Click(object sender, EventArgs e)
        {
            if (TDBCboVoucherTypeID.Text == "") { return; }
            Form frm = new frm0041(TDBCboVoucherTypeID.Text, TDBCboVoucherTypeID);
            frm.ShowDialog();
        }
    }
}
